package com.baizhi.controller;

import com.baizhi.entity.Record;
import com.baizhi.service.RecordService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class RecordController {

    @Autowired
    private RecordService recordService;
    //分页展示
    @GetMapping("/records")
    public Map show(@RequestParam(defaultValue = "1") Integer pageNum,
                    @RequestParam(defaultValue = "5")Integer pageSize){
        List<Record> list = recordService.selectAll(pageNum, pageSize);
        PageInfo<Record> pageInfo = new PageInfo<>(list, 10);
        long total = pageInfo.getTotal();
        int[] pages = pageInfo.getNavigatepageNums();

        HashMap<String, Object> map = new HashMap<>();
        map.put("list",list);
        map.put("pages",pages);
        map.put("total",total);
        return map;
    }
    //根据id删除
    @DeleteMapping(value = "/records/{id}")
    public Map remove(@PathVariable("id") Integer id){
        HashMap<String, Object> map = new HashMap<>();
        try {
            recordService.deleteById(id);
            map.put("status","success");
        } catch (Exception e) {
            map.put("status","failed");
            e.printStackTrace();
        }
        return map;
    }
    //根据获取某个信息
    @GetMapping(value = "/records/{id}")
    public Map showOne(@PathVariable("id") Integer id){
        System.out.println("id = " + id);
        HashMap<String, Object> map = new HashMap<>();
        try {
            Record record = recordService.selectById(id);
            map.put("status","success");
            map.put("record",record);
        } catch (Exception e) {
            map.put("status","failed");
            e.printStackTrace();
        }
        return map;
    }
    //修改某个信息
    @PutMapping(value = "/records")
    public Map updateOne(@RequestBody Record record){
        HashMap<String, Object> map = new HashMap<>();
        try {
            recordService.updateRecord(record);
            map.put("status","success");
        } catch (Exception e) {
            map.put("status","failed");
            e.printStackTrace();
        }
        return map;
    }
    //添加某个信息
    @PostMapping(value = "/records")
    public Map addOne(@RequestBody Record record){
        HashMap<String, Object> map = new HashMap<>();
        try {
            recordService.insertRecord(record);
            map.put("status","success");
        } catch (Exception e) {
            map.put("status","failed");
            e.printStackTrace();
        }
        return map;
    }
}
